package com.jingli.pile.demo;

public class ModbusCRC16 {
    private static final int CRC_POLY = 0xA001;

    public static int calculateCRC(byte[] data) {
        int crc = 0xFFFF;

        for (byte b : data) {
            crc ^= b & 0xFF;
            for (int i = 0; i < 8; i++) {
                if ((crc & 0x0001) != 0) {
                    crc = (crc >> 1) ^ CRC_POLY;
                } else {
                    crc >>= 1;
                }
            }
        }

        return crc & 0xFFFF;
    }

    public static void main(String[] args) {
        String hexData = "22e4dd00012023100500900001011056312e302e320000008986112222104111990400";
        byte[] data = hexToByteArray(hexData);
        int crc = calculateCRC(data);
        String crcHex = Integer.toHexString(crc).toUpperCase();
        System.out.println("CRC: " + crcHex);
    }

    private static byte[] hexToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }
}
